import csv
import open3d as o3d
import numpy as np
from PIL import Image
import os


def pure_color(index):
    gray = list(range(0, 256))
    empty = np.empty((256, 3), int)
    for i in range(0, 3):
        empty[:, i] = 0
    empty[:, index] = gray
    return empty


def to_ply_from_csv(csv_path):
    with open(csv_path) as csvfile:
        csv_reader = csv.reader(csvfile)
        data = list(csv_reader)
    data = [[int(j) for j in i] for i in data]

    pixel_values = np.array(data)

    for i in range(0, 3):
        pixel_values = np.concatenate((pixel_values, pure_color(i)), axis=0)

    pcd = o3d.geometry.PointCloud()
    pcd.points = o3d.utility.Vector3dVector(pixel_values)
    pcd.colors = pcd.colors = o3d.utility.Vector3dVector(pixel_values / 255.0)
    #o3d.io.write_point_cloud("cache.ply", pcd)
    # 获取 CSV 文件的同级目录路径
    directory = os.path.dirname(csv_path)
    # 生成 .ply 文件的完整路径
    ply_path = os.path.join(directory, "cache.ply")
    # 保存点云为 .ply 文件
    o3d.io.write_point_cloud(ply_path, pcd)
    # 返回保存的 .ply 文件路径
    return ply_path


def show_point_cloud(ply_file):
    pcd_load = o3d.io.read_point_cloud(ply_file)
    o3d.visualization.draw_geometries([pcd_load], window_name="Tunnel", width=1200, height=900, left=50, top=50)


def to_ply_from_image(image_path):
    image = Image.open(image_path)
    pixel_values = np.array(list(image.getdata()))

    if pixel_values.shape[1] > 3:
        pixel_values = np.delete(pixel_values, 3, 1)

    for i in range(0, 3):
        pixel_values = np.concatenate((pixel_values, pure_color(i)), axis=0)

    pcd = o3d.geometry.PointCloud()
    pcd.points = o3d.utility.Vector3dVector(pixel_values)
    pcd.colors = pcd.colors = o3d.utility.Vector3dVector(pixel_values / 255.0)

    o3d.io.write_point_cloud("cache.ply", pcd)


def example():
    to_ply_from_image("mess.jpg")
    show_point_cloud("cache.ply")
    to_ply_from_csv("dense.csv")
    show_point_cloud("cache.ply")
